﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ElectronicScale
{
    public class DBHelper
    {
        #region 单例模式
        private static DBHelper dbHelper = null;

        public static DBHelper GetDBHelper()
        {
            if (dbHelper == null) return dbHelper = new DBHelper();
            return dbHelper;
        }

        private DBHelper()
        {

        }
        #endregion

        private SqlConnection conn = null;
        private bool hasValid = false;

        public bool HasValid { get => hasValid; }

        #region 验证数据库配置
        /// <summary>
        /// 验证数据库配置
        /// </summary>
        /// <param name="address"></param>
        /// <param name="database"></param>
        /// <param name="uid"></param>
        /// <param name="pwd"></param>
        /// <param name="err"></param>
        /// <returns></returns>
        public bool Valid(string address, string database, string uid, string pwd, out string err)
        {
            err = null;
            try
            {
                conn = new SqlConnection(string.Format("server={0};database={1};uid={2};pwd={3}", address, database, uid, pwd));
                conn.Open();
                conn.Close();
                hasValid = true;
            }
            catch (Exception ex)
            {
                err = ex.Message;
                hasValid = false;
            }
            return HasValid;
        }
        #endregion

        public void SaveWeightData(double weight,DateTime timeStamp)
        {
            if (!HasValid) return;
                using (var cmd = conn.CreateCommand())
                {
                    SqlParameter[] parameters = new SqlParameter[] 
                    {
                        new SqlParameter("@Weight", weight),
                        new SqlParameter("@TimeStamp", timeStamp)
                    };
                    cmd.CommandText = "insert into Data Values(@Weight,@TimeStamp)";
                    if (conn.State != System.Data.ConnectionState.Open) conn.Open();
                    cmd.Parameters.AddRange(parameters);
                    cmd.ExecuteNonQuery();
                    conn.Close();
                }
        }
    }
}
